# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import time

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter

import random

from scrapy.http import HtmlResponse

from wangyi.settings import USER_AGENTS_LIST
from fake_useragent import UserAgent


class WangyiSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class WangyiDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # 处理代理ip 和 请求头
        # 采用配置文件方式进行设置
        # request.headers['User-Agent'] = random.choice(USER_AGENTS_LIST)
        # 使用fake_useragent的方式进行导入c
        request.headers['User-Agent'] = UserAgent().random
        return None

    def process_response(self, request, response, spider):
        # 处理获取到selenium 响应对应的代码
        # print(request.headers['User-Agent'])
        driver = spider.driver  # 获取selenium对象
        # 也就是我们请求的url 如果在selenium_url这个列表中  则代表需要使用selenium发起请求的
        url = request.url  # 获取访问的url
        if url in spider.selenium_url:
            # 访问异步网址
            driver.get(url)
            # 滚动到底部 目的把异步的数据加载完
            driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
            time.sleep(1)
            # 拖动两次
            driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
            time.sleep(1)
            # driver.execute_script('window.scrollBy(0, 1000000)')
            # driver.execute_script('window.scrollBy(0, 1000000)')
            # 好获取最终页面的源码
            res = driver.page_source
            # 手动构造响应 把selenium抓取的页面内容 响应回去
            return HtmlResponse(url, body=res, encoding='UTF-8', request=request)
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)
